package top.rzhsky.dao.impl;

import top.rzhsky.bean.Message;
import top.rzhsky.bean.User;
import top.rzhsky.dao.Dao;
import top.rzhsky.server.Config;
import top.rzhsky.util.QQCreate;

import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

public class UserDao implements Dao {

    private Logger logger = Logger.getLogger("UserDao");

    @Override
    public User login(Message message) {
        try {
            File accountDir = new File(Config.userPath);

            File[] files = accountDir.listFiles();

            if (files != null) {
                for (File file : files) {
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                    Message msg = (Message) ois.readObject();

                    String account = message.getFrom().getAccount();
                    if (file.getName().equals(account + ".dat") && message.getFrom().getPassword().equals(msg.getFrom().getPassword())) {
                        return msg.getFrom();
                    }
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            logger.warning("文件找不到");
        }
        return null;
    }

    @Override
    public HashSet<User> listAllUserName() {
        HashSet<User> set = new HashSet<>();
        try {
            File accountDir = new File("files");
            File[] files = accountDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                    Message message = (Message) ois.readObject();
                    set.add(message.getFrom());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return set;
    }

    @Override
    public User register(Message message) throws IOException {
        File dir = new File(Config.userPath);

        File file;
        ObjectOutputStream oos;
        String registerAccount;

        if (!dir.exists()) {
            dir.mkdir();
        }

        do {
            registerAccount = QQCreate.createQQ();
            file = new File(Config.userPath + "/" + registerAccount + ".dat");
        } while (file.exists());

        User user = message.getFrom();
        user.setAccount(registerAccount);

        oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(message);

        oos.close();
        return user;
    }
}
